package cn.itcast.mq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.ImmediateRequeueMessageRecoverer;
import org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description 消息重试耗尽处理配置类
 * @Author liuqiang
 * @Date 2024/3/23
 */
@Configuration
public class ErrorMessageConfig {

    @Bean
    public DirectExchange errorMessageExchange() {
        return new DirectExchange("error.direct");
    }

    @Bean
    public Queue errorQueue() {
        return new Queue("error.queue", true);
    }

    @Bean
    public Binding errorBinding() {
        return BindingBuilder.bind(errorQueue()).to(errorMessageExchange()).with("error");
    }

    /**
     * RepublishMessageRecoverer 重试耗尽后，将失败消息投递到指定的交换机(推荐使用)
     * @return
     */
    @Bean
    public RepublishMessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        //AmqpTemplate errorTemplate, String errorExchange, String errorRoutingKey
        return new RepublishMessageRecoverer(rabbitTemplate,"error.direct","error");
    }

    /**
     * ImmediateRequeueMessageRecoverer：重试耗尽后，返回nack，消息重新入队
     * @return
     */
    /*
    @Bean
    public ImmediateRequeueMessageRecoverer immediateRequeueMessageRecoverer(){
        return new ImmediateRequeueMessageRecoverer();
    }
    */
    /**
     * RejectAndDontRequeueRecoverer：重试耗尽后，直接reject，丢弃消息。默认就是这种方式
     * @return
     */
    /*
    @Bean
    public RejectAndDontRequeueRecoverer RejectAndDontRequeueRecoverer(){
        return new RejectAndDontRequeueRecoverer();
    }
    */

}
